package com.malou.client.pagos.pagoletras;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormButtonBinding;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.malou.client.MalouConstants;
import com.malou.client.MalouMessages;
import com.malou.client.util.Utilities;

public class RenovarLetraDialog extends Dialog {

	private MalouMessages messages = GWT.create(MalouMessages.class);	
	private TextField<String> txtBanco;
	private TextField<String> txtNumerodocumento;
	private TextField<String> txtNumeroletra;
	private TextField<String> txtMonto;
	private HiddenField<String> id;
	private HiddenField<String> banco_id;
	private HiddenField<String> proveedor_id;
	
	private TextField<String> txtNumeroletrahijo;

	private DateField fechavencimiento;
	private NumberField txtMontohijo;

	private Button btnAgregar;
	private Button btnGuardar;
	private Button btnLimpiar;
	private Button btnDelete;

	private FieldSet fsproveedor;
	private FieldSet fsLetra;
	private FormPanel panel;
	private ContentPanel panelgrid;
	
	private MalouConstants k = GWT.create(MalouConstants.class);
	private FormBinding formbinding;
	private Grid<BeanModel> grid;
	private ToolBar toolbar;

	private SelectionListener<ButtonEvent> sl_delete;
	private List<ColumnConfig> columns;
	private ColumnModel cm;
	
	private FormButtonBinding formbuttonbindig;
	private ListStore<BeanModel> store;

	public RenovarLetraDialog() {
		super();
		setButtons("");
		setSize(700, 450);
		setModal(false);
		setLayout(new BorderLayout());
		setModal(true);
		setResizable(false);
		setHeading(k.letraRenovar2());
		setOnEsc(true);

				
		btnAgregar = new Button(k.agregar(),	IconHelper.createPath("images/icons/new.gif"));
		btnDelete = new Button(k.eliminar(),	IconHelper.createPath("images/icons/delete.gif"));
		btnDelete.setEnabled(false);
		btnAgregar.setStyleAttribute("marginRight", "15px");
		btnGuardar = new Button(k.guardar());
		btnLimpiar = new Button(k.limpiar());
		
		SelectionListener<ButtonEvent> sl_guardar = new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				if(store.getCount()==0){						
					MessageBox.alert(k.sistemaMarcocruzado(), k.letraDetalleRequerido(), null);
					txtNumeroletra.focus();
					return;
				}
					List<Letra> list = new ArrayList<Letra>();
					Letra letra;
					for(BeanModel b:store.getModels()){
						letra = new Letra();
						letra.setLetrapadre_id(Integer.valueOf(id.getValue()));
						letra.setBanco_id(Integer.valueOf(banco_id.getValue()));
						letra.setProveedor_id(Integer.valueOf(proveedor_id.getValue()));
						letra.setFechavencimiento((Date)b.get("fechavencimiento"));
						letra.setMonto((Double)b.get("monto"));
						letra.setNumerodocumento(b.get("numerodocumento").toString());
						letra.setNumeroletra(b.get("numeroletra").toString());
						
						list.add(letra);
					}
					getButtonBar().disable();
					Letras.renovarletraDialog =RenovarLetraDialog.this;
					Letras.renovar(Integer.valueOf(id.getValue()), list);
				}
			
			
		};
		
		btnGuardar.addSelectionListener(sl_guardar);
		
		btnAgregar.addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				agregarDetalle();
				limpiarLetras();
				
				
			}
		});
		
		btnLimpiar.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				limpiarLetras();
				store.removeAll();
				
			}
		});
		
		toolbar = new ToolBar();
		toolbar.setBorders(true);
		toolbar.add(btnDelete);
		toolbar.add(btnAgregar);
 

		panel = new FormPanel();
		panel.setHeaderVisible(false);
		panel.setBodyBorder(false);
		panel.setLabelAlign(LabelAlign.TOP);
		
		
		formbinding=new FormBinding(panel);
		formbuttonbindig=new FormButtonBinding(panel);
		formbuttonbindig.addButton(btnAgregar);

		
		panelgrid = new ContentPanel();
		panelgrid.setHeaderVisible(false);
		panelgrid.setBodyBorder(false);
		panelgrid.setBorders(false);
		panelgrid.setStyleAttribute("padding", "10px");
		panelgrid.setLayout(new FitLayout());
		
         

		fsproveedor = new FieldSet();
		fsproveedor.setLayout(new ColumnLayout());
		fsproveedor.setCollapsible(false);
		fsproveedor.setHeading(k.letraOriginal());

		fsLetra = new FieldSet();
		fsLetra.setLayout(new ColumnLayout());
		fsLetra.setCollapsible(false);
		fsLetra.setHeading(k.letraFracionadas());

		id=new HiddenField<String>();
		banco_id=new HiddenField<String>();
		proveedor_id=new HiddenField<String>();
		
		panel.add(id);
		panel.add(banco_id);
		panel.add(proveedor_id);
		
		txtBanco = new TextField<String>();
		txtBanco.setFieldLabel(k.letraBanco());
		txtBanco.setReadOnly(true);
		Utilities.centrarTexto(txtBanco);

		txtNumeroletrahijo = new TextField<String>();
		txtNumeroletrahijo.setFieldLabel(k.letraNumeroUnico());
		txtNumeroletrahijo.setAllowBlank(false);
		txtNumeroletrahijo.focus();

		txtNumeroletra = new TextField<String>();
		txtNumeroletra.setReadOnly(true);
		txtNumeroletra.setFieldLabel(k.letraNumeroUnico());
		Utilities.centrarTexto(txtNumeroletra);

		txtNumerodocumento = new TextField<String>();
		txtNumerodocumento.setFieldLabel(k.letraNumeroDocumento());
		txtNumerodocumento.setReadOnly(true);
		Utilities.centrarTexto(txtNumerodocumento);
        		
		fechavencimiento = new DateField();
		fechavencimiento.setFieldLabel(k.letraFechaVencimiento());
		fechavencimiento.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		fechavencimiento.setAllowBlank(false);

		txtMonto = new TextField<String>();
		txtMonto.setFieldLabel(k.letraMonto());
		txtMonto.setReadOnly(true);
		Utilities.centrarTexto(txtMonto);
		
		txtMontohijo = new NumberField();
		txtMontohijo.setFieldLabel(k.letraMonto());
		txtMontohijo.setPropertyEditorType(Double.class);
		txtMontohijo.setAllowBlank(false);

		Component comp[]={txtNumeroletrahijo,fechavencimiento,txtMontohijo,btnAgregar};
		Utilities.Enter(comp);
		
		
		fsproveedor.add(setLayout(txtBanco, "90%"), new ColumnData(.40));
		fsproveedor.add(setLayout(txtNumeroletra, "90%"), new ColumnData(.20));
		fsproveedor.add(setLayout(txtNumerodocumento, "90%"), new ColumnData(.20));
		fsproveedor.add(setLayout(txtMonto, "100%"), new ColumnData(.20));
		
		
		fsLetra.add(setLayout(txtNumeroletrahijo,"80%"), new ColumnData(.34));
		fsLetra.add(setLayout(fechavencimiento, "80%"), new ColumnData(.34));
		fsLetra.add(setLayout(txtMontohijo, "80%"), new ColumnData(.20));
		fsLetra.add(setLayout2(btnAgregar, "0%"), new ColumnData(.12));

		panel.add(fsproveedor);
		panel.add(fsLetra);
		

		
		columns = new ArrayList<ColumnConfig>();
		columns.add(new ColumnConfig("numeroletra", k.letraNumeroUnico(), 200));
		columns.add(new ColumnConfig("numerodocumento", k.letraNumeroDocumento(), 150));
		columns.add(new ColumnConfig("monto", k.letraMonto(), 150));
		ColumnConfig fecha = new ColumnConfig("fechavencimiento", k.letraFechaVencimiento(),150);
		fecha.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));	
		columns.add(fecha);
		
		
		cm = new ColumnModel(columns);
		
		Letras.getPaginate();
		
		store = new ListStore<BeanModel>();
		
		grid = new Grid<BeanModel>(store, cm);
		grid.setAutoExpandColumn("numeroletra");
		grid.setLoadMask(true);
		grid.setBorders(true);
		grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {
			@Override
			public void handleEvent(GridEvent<BeanModel> be) {
				Letras.loader.load(0, Utilities.itemsPerPage);
			}
		});

		grid.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {

					@Override
					public void handleEvent(SelectionChangedEvent<BeanModel> be) {
						if(be.getSelectedItem() != null)
							btnDelete.setEnabled(true);
						else
							btnDelete.setEnabled(false);					

					}

				});	

		
		sl_delete = new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				BeanModel be =grid.getSelectionModel().getSelectedItem();
				grid.getStore().remove(be);

			}
		};

		btnDelete.addSelectionListener(sl_delete);
		

		panelgrid.setTopComponent(toolbar);
		panelgrid.add(grid);
		
	    add(panel,new BorderLayoutData(LayoutRegion.NORTH,180));
	    add(panelgrid,new BorderLayoutData(LayoutRegion.CENTER));
	
	
	    addButton(btnGuardar);
		addButton(btnLimpiar);
		setButtonAlign(HorizontalAlignment.RIGHT);
	     
		setStore(Letras.store);

	}

	private LayoutContainer setLayout(Component comp, String porcentaje) {

		LayoutContainer lc5 = new LayoutContainer();
		FormLayout fl = new FormLayout(LabelAlign.TOP);
		fl.setLabelPad(0);

		lc5.setLayout(fl);
		lc5.setStyleAttribute("marginTop", "0px");
		lc5.add(comp, new FormData(porcentaje));
		
		return lc5;
	}

	private LayoutContainer setLayout2(Component comp, String porcentaje) {
		panel.setLabelAlign(LabelAlign.LEFT);
		LayoutContainer lc5 = new LayoutContainer();
		FormLayout fl = new FormLayout(LabelAlign.LEFT);
		fl.setLabelPad(0);
				
		lc5.setLayout(fl);
		lc5.setStyleAttribute("marginTop", "18px");
		lc5.add(comp, new FormData(porcentaje));
	
		return lc5;
	}
	

	public void setStore(ListStore<BeanModel> store) {

		formbinding.addFieldBinding(new FieldBinding(id, "id"));
		formbinding.addFieldBinding(new FieldBinding(banco_id, "banco_id"));
		formbinding.addFieldBinding(new FieldBinding(proveedor_id, "proveedor_id"));
		formbinding.addFieldBinding(new FieldBinding(txtBanco, "banco"));
		formbinding.addFieldBinding(new FieldBinding(txtNumeroletra, "numeroletra"));
		formbinding.addFieldBinding(new FieldBinding(txtNumerodocumento, "numerodocumento"));
		formbinding.addFieldBinding(new FieldBinding(txtMonto, "monto"));
		formbinding.setStore(store);
	}

	
	public void reset() {
		id.clear();
		banco_id.clear();
		proveedor_id.clear();
		txtBanco.clear();
		txtNumerodocumento.clear();
		txtNumeroletra.clear();
		txtMonto.clear();
		
		limpiarLetras();
	
		store.removeAll();
		unbind();

	}

	public void bind(BeanModel selectedModel) {
		formbinding.bind(selectedModel);
	}

	public void unbind() {
		formbinding.unbind();
	}
	
	
	private boolean isValidNumeroLetra(){
		boolean valor = true;
			String numero = txtNumeroletrahijo.getValue().trim();
			for(BeanModel b:store.getModels()){
				String num = b.get("numeroletra").toString().trim();
				if(num.equals(numero)){
					valor = false;
					String msg = messages.letraYaExisteLetra(numero);
					MessageBox.alert(k.sistemaMarcocruzado(), msg, null);
					txtNumeroletrahijo.focus();
				}
				
			}
		
		return valor;
		
	}
	
	public void agregarDetalle(){
		if(isValidNumeroLetra()){
			Letra letra = new Letra();
			letra.setNumeroletra(txtNumeroletrahijo.getValue());
			letra.setFechavencimiento(fechavencimiento.getValue());
			letra.setMonto((Double)txtMontohijo.getValue());
			letra.setNumerodocumento(txtNumerodocumento.getValue());
			
			BeanModelFactory beanModelFactory =  BeanModelLookup.get().getFactory(letra.getClass());
	    	store.add(beanModelFactory.createModel(letra));
	    	
	    	
		}
	}	

	
	public void limpiarLetras(){
		txtNumeroletrahijo.clear();
		fechavencimiento.clear();
		txtMontohijo.clear();
		txtNumeroletrahijo.focus();
		

	}
}
